public static void main(String[] args) throws UnsupportedEncodingException { CloseableHttpClient client = HttpClients.custom().build(); HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/httpClient"); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // multipartEntityBuilder.setCharset(Charset.forName("utf-8")); FileBody file = new FileBody(new File("F:\\壁纸\\b.jpg")); multipartEntityBuilder.addPart("file", file); multipartEntityBuilder.addTextBody("name", "tanghaibin"); multipartEntityBuilder.addBinaryBody("lick", "骑行".getBytes("utf-8")); httpPost.setEntity(multipartEntityBuilder.build()); try { CloseableHttpResponse response = client.execute(httpPost); HttpEntity result = response.getEntity(); System.out.println(result.toString()); } catch (IOException e) { e.printStackTrace(); } }
private String login(int... ids) { Log.d(TAG, "login(ids... method start"); String result = ""; String result2 = ""; ArrayList<RecipeGeneral> recipes = null; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(Constants.URL_LOGIN); httpget.setHeader("Accept", "application/json"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); Log.d(TAG, "Login form get: " + response.getStatusLine()); Log.d(TAG, "Entity: " + entity.toString()); if (entity != null) { result = HttpFactory.convertStreamToString(entity.getContent()); Log.d(TAG, "Result: " + result); } List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.d(TAG, "No cookies"); } else { for (int i = 0; i < cookies.size(); i++) { Log.d(TAG, "Cookies: " + cookies.get(i).toString()); } } JSONObject jsonResponse = new JSONObject(result.trim()); Log.d(TAG, "jsonResponce: " + jsonResponse.toString()); String token_value = jsonResponse.getString("token_value"); String token_name = jsonResponse.getString("token_name"); Log.d(TAG, "token_value: " + token_value); Log.d(TAG, "token_name: " + token_name); HttpPost httpost = new HttpPost(Constants.URL_LOGIN); httpost.setHeader("Accept", "application/json"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("user[email]", login)); nvps.add(new BasicNameValuePair("user[password]", password)); nvps.add(new BasicNameValuePair(token_name, token_value)); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response1 = httpclient.execute(httpost); HttpEntity entity1 = response1.getEntity(); Log.d(TAG, "Login form post: " + response1.getStatusLine()); if (entity1 != null) { result = HttpFactory.convertStreamToString(entity1.getContent()); Log.d(TAG, "Entity: " + result); } StringBuilder idsParams = new StringBuilder(); for (int id : ids) { idsParams.append("&ids[]=" + id); } HttpGet httpget2 = new HttpGet(Constants.URL_SYNC + "?ids[]=0" + idsParams); httpget2.setHeader("Accept", "application/json"); Log.d(TAG, "Request line: " + httpget2.getRequestLine()); Log.d(TAG, "Request params: " + httpget2.getParams()); Log.d(TAG, "Request uri: " + httpget2.getURI()); HttpResponse response2 = httpclient.execute(httpget2); HttpEntity entity2 = response2.getEntity(); Log.d(TAG, "Login form get2: " + response2.getStatusLine()); Log.d(TAG, "Entity2: " + entity2.toString()); if (entity2 != null) { result2 = HttpFactory.convertStreamToString(entity2.getContent()); Log.d(TAG, "Result2: " + result2); } List<Cookie> cookies2 = httpclient.getCookieStore().getCookies(); if (cookies2.isEmpty()) { Log.d(TAG, "No cookies2 "); } else { for (int i = 0; i < cookies2.size(); i++) { Log.d(TAG, "Cookies2 : " + cookies2.get(i).toString()); } } } catch (Exception e) { e.printStackTrace(); receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null); } return result2; }
@Override protected String doInBackground(Void... voidstr) { JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("firstName", firstName); jsonObject.accumulate("lastName", lastName); jsonObject.accumulate("phoneNumber", phoneNumber); jsonObject.accumulate("address", addr); // Add a nested JSONObject (e.g. for header information) JSONObject header = new JSONObject(); header.put("deviceType", "Android"); // Device type header.put("deviceVersion", "2.0"); // Device OS version header.put("language", "es-es"); // Language of the Android client jsonObject.put("header", header); // Output the JSON object we're sending to Logcat: URL = "http://162.243.114.166/cgi-bin/Database_scripts/Registration_script.py"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); System.out.println("printing json object : " + jsonObject); String se; se = jsonObject.toString(); System.out.println("printing se : " + se); // Set HTTP parameters httpPostRequest.setEntity(se); System.out.println("printing req : " + httpPostRequest.getEntity().getContent().toString()); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); // httpPostRequest.setHeader("Content-length", IntegejsonObjSend.toString().length()); // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you // would like to use gzip compression InputStream inp = httpPostRequest.getEntity().getContent(); String req = convertStreamToString(inp); System.out.println("printing entities : " + req); System.out.println("printing http request message : message is :" + httpPostRequest); HttpResponse response = null; try { response = (HttpResponse) httpclient.execute(httpPostRequest); } catch (Exception ex) { System.out.println("printing error :" + ex); } InputStream is = response.getEntity().getContent(); String res = convertStreamToString(is); System.out.println("printing Response is :" + res); System.out.println("printing response code : " + response.getStatusLine().getStatusCode()); // Get hold of the response entity (-> the data) HttpEntity entity = response.getEntity(); String serverresp = entity.toString(); System.out.println( "printing server response, entity length : " + entity.getContentLength()); System.out.println("printing server response : " + serverresp); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } System.out.println("Debug point : 1.3"); // convert content stream to a String String resultString = convertStreamToString(instream); instream.close(); resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONObject jsonObjRecv = new JSONObject(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); System.out.println("Debug point : 1.4"); return jsonObjRecv; } // return serverresp; try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("q", se)); httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); System.out.println("printing http params: " + httpPostRequest.getParams().toString()); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpPostRequest); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } catch (Exception e) { System.out.println("Debug point : 1.4(a)"); // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }