我对PHP、JavaScript和许多其他脚本语言很有经验,但我对Java或Android没有太多经验。
我正在寻找一种方法将POST数据发送到PHP脚本并显示结果。
我对PHP、JavaScript和许多其他脚本语言很有经验,但我对Java或Android没有太多经验。
我正在寻找一种方法将POST数据发送到PHP脚本并显示结果。
当前回答
下面是一个完整的解决方案,它运行在后台线程中,向Web API发送一个HTTPS POST多部分请求。实际测试和工作代码。注意:“\n”字符需要在顶部的“最终字符串”中进行正确的请求格式化。
我有困难要么理解,转换,或完成以上解决方案,我的多部分POST需求。
@Override
protected Integer doInBackground(String... files) {
final String MULTIPART_BOUNDARY = "xxYYzzSEPARATORzzYYxx";
final String MULTIPART_SEPARATOR = "--" + MULTIPART_BOUNDARY + "\n";
final String MULTIPART_FORM_DATA = "Content-Disposition: form-data; name=\"%s\"\n\n";
final String FORM_DATA_FILE1 = "file1";
final String FORM_DATA_FILE2 = "file2";
OutputStream outputStream;
Integer responseCode = 0;
try {
URL url = new URL("https://www.example.com/api/endpoint?n1=v1&n2=v2");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + MULTIPART_BOUNDARY);
urlConnection.setConnectTimeout(6000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.write(MULTIPART_SEPARATOR);
writer.write(String.format(MULTIPART_FORM_DATA, FORM_DATA_FILE1));
writer.write(files[0]);
writer.write(MULTIPART_SEPARATOR);
writer.write(String.format(MULTIPART_FORM_DATA, FORM_DATA_FILE2));
writer.write(files[1]);
writer.write(MULTIPART_SEPARATOR);
writer.flush();
writer.close();
outputStream.close();
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
Log.d("ResponseCode:", String.valueOf(responseCode));
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return responseCode;
}
其他回答
你可以使用URLConnection setDoOutput(true), getOutputStream()(用于发送数据),和getInputStream()(用于接收)。Sun在这方面有一个例子。
如果你只是想把数据附加到Url,你可以通过使用httppurlconnection来实现,因为HttpClient现在已经弃用了。 更好的方法是使用像-这样的库
凌空抽射 改造
我们可以将数据发送到php脚本,并通过使用AsyncTask类执行的代码来获取结果并显示它。
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
String data ="";
int sizeData = 0;
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
Dialog.setCancelable(false);
Dialog.setCanceledOnTouchOutside(false);
try{
// Set Request parameter
data +="&" + URLEncoder.encode("username", "UTF-8") + "="+edittext.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);//define connection timeout
conn.setReadTimeout(5000);//define read timeout
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(),"Error encountered",Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject jsonRootObject = new JSONObject(Content);
JSONObject json2 =jsonRootObject.getJSONObject("jsonkey");//pass jsonkey here
String id =json2.optString("id").toString();//parse json to string through parameters
//the result is stored in string id. you can display it now
} catch (JSONException e) {e.printStackTrace();}
}
}
}
但是使用诸如volley或retrofit之类的库是更好的选择,因为Asynctask类和HttpurlConnection相比库更慢。此外,库将获取所有内容,也更快。
在新版本的Android中,你必须把所有的web I/O请求放到一个新的线程中。AsyncTask最适合小请求。
最好使用Apache Commons HttpClient,它已经包含在android中了。 看一看 Android开发人员:Apache HTTP客户端包摘要 一般API信息。
对我来说,接下来的工作是:
private sendData() {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("key1", value1);
jsonObject.accumulate("key2", value2);
boolean success = sendPost(SERVER_URL + "/v1/auth", jsonObject);
}
private boolean sendPost(String url, JSONObject parameters) {
boolean requestResult = false;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
json = parameters.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
requestResult = true;
} else {
result = "Did not work!";
requestResult = false;
}
System.out.println(result);
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
requestResult = false;
}
return requestResult;
}