在Android上的AsyncTask中对HTTPURLCONNECTION进行POST的最简单方法是什么? 我只想在我的php文件上发布数据,然后返回一个json响应
答案 0 :(得分:2)
你可以从我前几天给你的答案中把它拼凑起来: How to get JSON object using HttpURLConnection instead of Volley?
......答案在这里:Java - sending HTTP parameters via POST method easily
话虽这么说,开始发送POST数据并获得JSON结果的最简单方法是使用旧的API。
这是一个有效的例子:
class CreateNewProduct extends AsyncTask<String, String, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ShareNewMessage.this);
pDialog.setMessage("Sharing Message...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected JSONObject doInBackground(String... args) {
String message = inputMessage.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", username));
params.add(new BasicNameValuePair("message", message));
Log.d("Share", "Sharing message, username: " + username + " message: " + message);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_create_message);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Share", "Error converting InputStream result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("Share", "Error parsing JSON data " + e.toString());
}
try{
int success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject jObj) {
//do something with jObj
// dismiss the dialog once done
pDialog.dismiss();
}
}
答案 1 :(得分:0)
以下是如何将图像上传到服务器的示例代码
class ImageUploadTask extends AsyncTask <Void, Void, String>{
@Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
getString(R.string.WebServiceURL)
+ "/cfc/iphonewebservice.cfc?method=uploadPhoto");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("photoId", new StringBody(getIntent()
.getStringExtra("photoId")));
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));
entity.addPart("photoCaption", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
有关此问题的完整教程,请浏览this。
在上面的代码中,您只需添加
即可发送要发送的任何表单数据entity.addPart("value", new StringBody(key));
答案 2 :(得分:0)
试一下
public class parseProduct extends AsyncTask<Void, Void, Void> {
String jsonResponse;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
JSONObject object = new JSONObject();
try {
object.put("registeruserid", userId); // you can pass data which you want to pass from POST
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonResponse=getResponseStringFromURL2(URL,object.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void resul) {
super.onPostExecute(resul);
}
}
以下是功能:
public String getResponseStringFromURL2(String url, String json)
throws ClientProtocolException, IOException {
StringBuilder result = new StringBuilder();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost request = new HttpPost(url);
if (json != null) {
StringEntity se = new StringEntity(json);
request.setEntity(se);
}
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
Log.d("request: ", ":" + request.getRequestLine());
HttpResponse response = null;
response = httpClient.execute(request);
if (response == null)
return null;
InputStream input = null;
input = new BufferedInputStream(response.getEntity().getContent());
byte data[] = new byte[40000];
int currentByteReadCount = 0;
/** read response from inpus stream */
while ((currentByteReadCount = input.read(data)) != -1) {
String readData = new String(data, 0, currentByteReadCount);
result.append(readData);
}
input.close();
return result.toString();
}