easy way to do POST on HTTPURLConnection?
本问题已经有最佳答案,请猛点这里访问。
在Android的AsyncTask中,在httpurlConnection上发布日志最简单的方法是什么?我只想在php文件上发布数据,然后返回json响应
你可以从我前几天给你的答案中拼凑出来:如何使用httpurlconnection而不是volley获取JSON对象?
…这里的答案是:Java-轻松地通过POST方法发送HTTP参数
也就是说,开始发送POST数据和获得JSON结果的最简单方法就是使用旧的API。
下面是一个工作示例:
2试试这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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); } } |
功能如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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(); } |
以下是如何将图像上载到服务器的示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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); } |
有关这方面的完整教程,请仔细阅读。
在上面的代码中,只需添加
1 |