@Override protected String doInBackground(String... params) { byte[] result = null; String str = ""; HttpClient client = new DefaultHttpClient(); // HttpGet request = new // HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"+mSettings.getString(APP_PREFERENCES_TOKENID,"tokenId")); HttpGet request = new HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"); HttpResponse response; try { response = client.execute(request); result = EntityUtils.toByteArray(response.getEntity()); str = new String(result, "UTF-8"); Log.d("Response of GET request", response.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str; }
public static Long getProjectIdByName(String projectName, RestClient restClient) { Long projectId = 0L; HttpResponse response = null; try { response = restClient .getHttpclient() .execute( new HttpGet( restClient.getUrl() + "/flex/services/rest/latest/project?name=" + URLEncoder.encode(projectName, "utf-8")), restClient.getContext()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { JSONArray projArray = new JSONArray(string); List<Long> projectIdList = new ArrayList<Long>(); for (int i = 0; i < projArray.length(); i++) { Long id = projArray.getJSONObject(i).getLong("id"); projectIdList.add(id); } Collections.sort(projectIdList); projectId = projectIdList.get(0); } catch (JSONException e) { e.printStackTrace(); } } else { try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return projectId; }
/*public static double getTescoTotal(String barcode) throws JSONException { double parsedvalue= JsonObject.getTescoProductValue(barcode); //int i= Integer.parseInt(parsedvalue); int total = 0; while(parsedvalue!=0) { total+=parsedvalue; } return total; }*/ public static String getTescoProductName(String barcode) throws JSONException { String key = "empty"; key = login(); String URL = startURL + key + "&SEARCHTEXT=" + barcode; // InputStream is=null; HttpClient httpclient = new DefaultHttpClient(); HttpGet request = new HttpGet(URL); request.addHeader("deviceId", deviceId); ResponseHandler<String> handler = new BasicResponseHandler(); try { result = httpclient.execute(request, handler); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } jObject = new JSONObject(result); JSONArray productinfo = jObject.getJSONArray("Products"); String name = null; for (int i = 0; i < productinfo.length(); i++) { name = productinfo.getJSONObject(i).getString("Name").toString(); } return name; }
/** * this method delete a particular Contact in zoho.com and returns success message with deleted * Contact id. This method takes input as a MAP(contains json dada) and returns a MAP. * * @param outMap */ private Map<String, String> delete(Map<String, String> outMap) { List<NameValuePair> contactAttrList = new ArrayList<NameValuePair>(); contactAttrList.add(new BasicNameValuePair(OAUTH_TOKEN, args.get(AUTHTOKEN))); contactAttrList.add(new BasicNameValuePair(ZOHO_SCOPE, SCOPE)); contactAttrList.add(new BasicNameValuePair(ID, args.get(ID))); TransportTools tst = new TransportTools(ZOHO_CRM_CONTACT_JSON_URL + DELETE_RECORDS, contactAttrList); String responseBody = null; TransportResponse response = null; try { response = TransportMachinery.post(tst); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } responseBody = response.entityToString(); outMap.put(OUTPUT, responseBody); return outMap; }
public static void connect(String url) { HttpClient httpclient = new DefaultHttpClient(); // Prepare a request object HttpGet httpget = new HttpGet(url); // Execute the request HttpResponse response; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); mResult = convertStreamToString(instream); // JSONObject json=new JSONObject(result); instream.close(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } }
private String doGet(String url) { String responseStr = ""; try { HttpGet httpRequest = new HttpGet(url); HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, 1000); HttpConnectionParams.setConnectionTimeout(params, 3000); HttpConnectionParams.setSoTimeout(params, 5000); httpRequest.setParams(params); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); final int ret = httpResponse.getStatusLine().getStatusCode(); if (ret == HttpStatus.SC_OK) { responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); } else { responseStr = "-1"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return responseStr; }
/** * 获取jsapi_ticket * * @param accesstoken * @return */ public static void getjsTicket(String accesstoken) { String jsapi_ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; String url = jsapi_ticketUrl.replace("ACCESS_TOKEN", accesstoken); System.out.println("查看js_url:" + url); try { if (jsTicket.equals("")) { String result = HttpUtil.getInstance().execGet(url); logger.debug("result==" + result); JSONObject obj = JSONObject.fromObject(result); if (obj.containsKey("ticket")) { jsTicket = obj.get("ticket").toString(); System.out.println("ticket====" + obj.get("ticket")); } else { getAccessToken(); getjsTicket(accessToken); return; } } else { } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Getting XML from URL making HTTP request * * @param url string */ public String getXmlFromUrl(String url) { String xml = null; DefaultHttpClient httpClient = new DefaultHttpClient(); try { // defaultHttpClient HttpGet httpPost = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NetworkOnMainThreadException e) { e.printStackTrace(); } // return XML return xml; }
protected MjpegInputStream doInBackground(String... url) { // TODO: if camera has authentication deal with it and don't just not work HttpResponse res = null; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 5 * 1000); if (DEBUG) Log.d(TAG, "1. Sending http request"); try { res = httpclient.execute(new HttpGet(URI.create(url[0]))); if (DEBUG) Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode()); if (res.getStatusLine().getStatusCode() == 401) { // You must turn off camera User Access Control before this will work return null; } return new MjpegInputStream(res.getEntity().getContent()); } catch (ClientProtocolException e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "Request failed-ClientProtocolException", e); } // Error connecting to camera } catch (IOException e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "Request failed-IOException", e); } // Error connecting to camera } return null; }
public boolean check_connect_status() { try { // Message ma=main_thread_handler.obtainMessage(1,"try!"); // main_thread_handler.sendMessage(ma); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network_info = cm.getActiveNetworkInfo(); if (network_info == null || network_info.isConnected() == false) { // Toast.makeText(this, "網路狀態:關閉", Toast.LENGTH_SHORT).show(); Message m = main_thread_handler.obtainMessage(4, "請開啟網路"); main_thread_handler.sendMessage(m); return false; } else { // Toast.makeText(this, "網路狀態:開啟", Toast.LENGTH_SHORT).show(); } if (connect_to_server("/project/mobilephone/check_connect.php", null).equals("1")) { // Toast.makeText(this, "可連接至主機", Toast.LENGTH_SHORT).show(); return true; } else { // Toast.makeText(this, "not connect", Toast.LENGTH_SHORT).show(); return false; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { Message m = main_thread_handler.obtainMessage(4, "無法連接至主機"); main_thread_handler.sendMessage(m); e.printStackTrace(); } return false; }
@Override protected String doInBackground(Integer... params) { int ItemPosition = params[0]; String ItemID = item_list.get(ItemPosition).get("item"); String Store = item_list.get(ItemPosition).get("store"); String Value = item_list.get(ItemPosition).get("number"); String StoreType = item_list.get(ItemPosition).get("StoreType"); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("CustomID", UserIMEI)); nameValuePairs.add(new BasicNameValuePair("ItemID", ItemID)); nameValuePairs.add(new BasicNameValuePair("Store", Store)); nameValuePairs.add(new BasicNameValuePair("Value", Value)); nameValuePairs.add(new BasicNameValuePair("StoreType", StoreType)); try { String result = connect_to_server("/project/mobilephone/DeleteItem.php", nameValuePairs); Log.v("debug", result); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
// 一个创建简单的连接客户端的链接方法 public static String easyLinkInternet(String request) { String str_entity = "值为null"; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(myWebUrl + request); // 这里的HttpGet应该是相当于HttpRequest try { HttpResponse httpResponse = httpClient.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); System.out.println(statusCode); if (statusCode == 200) { // 200的响应码代表的是连接成功且执行良好 Log.d("tag", "success_statusCode==200"); HttpEntity entity = httpResponse.getEntity(); // 将entity中的数据转化成字符串——得到json str_entity = EntityUtils.toString(entity); // 将entity中的数据转化成字符串——得到服务器返回的字符串 // str_entity = entity.toString(); System.out.println(str_entity); } } catch (ClientProtocolException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return str_entity; }
@Override protected String doInBackground(String... data) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { response = httpclient.execute(new HttpGet(url)); Log.e("HTTPClient", "Path = " + url); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); } else { // Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { e.printStackTrace(); onErrorResponse(e); } catch (IOException e) { e.printStackTrace(); onErrorResponse(e); } return responseString; }
/** 将设备Token提交服务器 */ public void postDeviceTokenToServiceLocked() { DebugUtils.logD(TAG, "postDeviceTokenToServiceLocked()"); try { if (MyAccountManager.getInstance().hasLoginned() && !TextUtils.isEmpty(getDeviceTotke()) && !getDeviceTotkeStatus()) { InputStream is = NetworkUtils.openContectionLocked( HaierServiceObject.getUpdateDeviceTokenUrl( String.valueOf(MyAccountManager.getInstance().getAccountObject().mAccountUid), getDeviceTotke(), "android"), MyApplication.getInstance().getSecurityKeyValuesObject()); if (is != null) { HaierResultObject result = HaierResultObject.parse(NetworkUtils.getContentFromInput(is)); NetworkUtils.closeInputStream(is); saveDeviceTokenStatus(result.isOpSuccessfully()); DebugUtils.logD(TAG, result.toString()); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override public void run() { // TODO Auto-generated method stub int result; String target = myapplication.getlocalhost() + "adduserzaninfo.php"; HttpPost httprequest = new HttpPost(target); List<NameValuePair> paramsList = new ArrayList<NameValuePair>(); paramsList.add(new BasicNameValuePair("_userid", myapplication.getUserId())); // 本人 paramsList.add(new BasicNameValuePair("_guid", guid)); // 本人 paramsList.add(new BasicNameValuePair("_action", gzaction)); // 本人 try { httprequest.setEntity(new UrlEncodedFormEntity(paramsList, "UTF-8")); HttpClient HttpClient1 = CustomerHttpClient.getHttpClient(); HttpResponse httpResponse = HttpClient1.execute(httprequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String json = EntityUtils.toString(httpResponse.getEntity()); result = Integer.parseInt(json); } else { result = 0; } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public String getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); 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"); } json = sb.toString(); is.close(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return json; }
@Override protected Object doInBackground(Object... params) { // TODO Auto-generated method stub try { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); String website = "http://myflickpicks.net/php/db/deleteusermovie.php?UserID=" + currentUser.getId() + "&MovieTitle=" + params[0].toString().replace(" ", "%20"); HttpGet httpGet = new HttpGet(website); httpGet.setHeader("accept", "application/json"); HttpResponse response = httpClient.execute(httpGet, localContext); // Toast.makeText(getActivity().getApplicationContext(), "Adding", // Toast.LENGTH_LONG).show(); // For example Log.v("MyDebug", "Door 1"); Log.v("MyDebug", currentUser.getId()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.v("MyDebug", "Door 2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.v("MyDebug", "Door 3"); } return null; }
public void run() { try { String ItemID = item_list.get(ItemPosition).get("item"); String Store = item_list.get(ItemPosition).get("store"); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("CustomID", UserIMEI)); nameValuePairs.add(new BasicNameValuePair("ItemID", ItemID)); nameValuePairs.add(new BasicNameValuePair("Store", Store)); String result = connect_to_server("/project/mobilephone/GetMyItem.php", nameValuePairs); String key[] = {"NeedValue", "TakenItemID", "ItemName", "Price"}; MyItemList = json_deconde(result, key); Message m = main_thread_handler.obtainMessage(8); main_thread_handler.sendMessage(m); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private HttpResponse executeHttpCleint(HttpPost httpPost, DefaultHttpClient httpClient) { HttpResponse response; int timeouts = 0; while (true) { try { response = httpClient.execute(httpPost); break; } catch (ClientProtocolException e1) { e1.printStackTrace(); Log.e(Global.TAG, "response error"); return null; } catch (IOException e1) { e1.printStackTrace(); Log.e(Global.TAG, "response error"); ++timeouts; if (timeouts == 2) { return null; } changeServer(httpPost, Global.API_JSON_ADDRESS); continue; } } return response; }
public void CancelChangeNumber() { try { String ItemID = item_list.get(ItemPosition).get("item"); String Store = item_list.get(ItemPosition).get("store"); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("CustomID", UserIMEI)); nameValuePairs.add(new BasicNameValuePair("ItemID", ItemID)); nameValuePairs.add(new BasicNameValuePair("Store", Store)); String result = connect_to_server("/project/mobilephone/CancelChangeNumber.php", nameValuePairs); if (result.equals("1")) { Message m = main_thread_handler.obtainMessage(1, "取消換號配對成功"); main_thread_handler.sendMessage(m); } else { Message m = main_thread_handler.obtainMessage(1, "取消換號配對失敗"); main_thread_handler.sendMessage(m); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); } }
public void run() { try { String ItemID = item_list.get(ItemPosition).get("item"); String Store = item_list.get(ItemPosition).get("store"); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("CustomID", UserIMEI)); nameValuePairs.add(new BasicNameValuePair("ItemID", ItemID)); nameValuePairs.add(new BasicNameValuePair("Store", Store)); nameValuePairs.add(new BasicNameValuePair("Choose", Integer.toString(Choose))); String result = connect_to_server("/project/mobilephone/ChangeNumberRequest.php", nameValuePairs); Message m = main_thread_handler.obtainMessage(5, Integer.toString(ItemPosition)); main_thread_handler.sendMessage(m); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ; }
/** * 该操作是一个阻塞联网操作,不能放在UI线程 Http://www.mingdown.com/cell/ adddownloadrecord.aspx?MM=下载的名片名号 * &&cell=下载人的默认本机号码 * * @param downloadedMm 下载的名片名号 * @param tel 下载人的默认本机号码 * @return */ public static boolean recordDownloadLocked(String downloadedMm, String tel) { DebugUtils.logD(TAG, "recordDownloadLocked downloadedMm=" + downloadedMm + " tel=" + tel); if (TextUtils.isEmpty(tel)) { DebugUtils.logD(TAG, "tel is empty, so we just return true"); return true; } StringBuilder sb = new StringBuilder(mDownloadRecordUriPrefix); sb.append("MM=").append(downloadedMm).append("&&cell=").append(tel); InputStream is = null; try { is = NetworkUtils.openContectionLocked( sb.toString(), MyApplication.getInstance().getSecurityKeyValuesObject()); DebugUtils.logD(TAG, "record download successfully."); return true; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; }
public static JSONObject doPost(String url, JSONObject obj) { JSONObject json = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); StringEntity se = new StringEntity(obj.toString()); httpPost.setEntity(se); HttpResponse response; response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result = convertStreamToString(instream); json = new JSONObject(result); instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return json; }
public String postUser(String username) { String uri = "http://10.0.2.2:8090/user"; List<NameValuePair> passParams = new ArrayList<NameValuePair>(1); passParams.add(new BasicNameValuePair("username", username)); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri); // Log.d("loltale:params", Integer.toString(params.length)); try { httpPost.setEntity(new UrlEncodedFormEntity(passParams)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
@Override protected String doInBackground(String... params) { String msg = params[0]; Log.d("CHAT_ROOM_ACTIVITY", msg); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(ServerData.IP); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair(ServerData.REQUEST_TYPE, ServerData.SEND_MESSAGE)); nameValuePairs.add(new BasicNameValuePair(ServerData.SELF_ID, selfId)); nameValuePairs.add(new BasicNameValuePair(ServerData.TARGET_ID, friendId)); nameValuePairs.add(new BasicNameValuePair(ServerData.MESSAGE, msg)); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = httpClient.execute(httpPost, responseHandler); return response; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public String httpGetAPICall(String requestURL) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(requestURL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(MainActivity.class.toString(), "Failedet JSON object"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
private HttpResponse HttpClientPost(String URL, String upload) { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); HttpClient httpclient = new DefaultHttpClient(httpParams); try { HttpPost post = new HttpPost(URL); post.addHeader("content-type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(upload)); HttpResponse response = httpclient.execute(post); return response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
public String getJSONFromUrl(String url) { // Making HTTP request try { HttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpGet httpPost = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); returnJsonAsString = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return returnJsonAsString; }
@Override protected String doInBackground(Void... params) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(ServerData.IP); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add( new BasicNameValuePair(ServerData.REQUEST_TYPE, ServerData.FETCH_MESSAGES_REQUEST)); nameValuePairs.add(new BasicNameValuePair(ServerData.SELF_ID, selfId)); try { Log.d("SEND REQUEST", "Sending request"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = httpClient.execute(httpPost, responseHandler); Log.d("RECEIVED MESSAGE", response); return response; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }