public static String postStream(String url, String data) { InputStream is = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(data)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse httpResponse = httpClient.execute(httpPost); Log.i("Httpresponse:", httpResponse.toString()); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (IOException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } Log.e("is:", is.toString()); return readStream(is); }
public static String postStream2(String url, String data) { InputStream is = null; String flag = ""; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(data)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse httpResponse = httpClient.execute(httpPost); Log.i("Httpresponse:", httpResponse.toString()); Log.i("Http Response:", String.valueOf(httpResponse.getStatusLine().getStatusCode())); if (String.valueOf(httpResponse.getStatusLine().getStatusCode()).trim().equals("404")) { flag = "false"; } else { flag = "true"; } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (IOException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } Log.e("is:", is.toString()); return flag; }
/** * Posting feedback or error info to the server. This is called from the AsyncTask. * * @param url The url to post the feedback to. * @param type The type of the info, eg Feedback.TYPE_CRASH_STACKTRACE. * @param feedback For feedback types this is the message. For error/crash types this is the path * to the error file. * @param groupId A single time generated ID, so that errors/feedback send together can be grouped * together. * @param index The index of the error in the list * @return A Payload file showing success, response code and response message. */ public static Payload postFeedback( String url, String type, String feedback, String groupId, int index, Application app) { Payload result = new Payload(null); List<NameValuePair> pairs = null; if (!isErrorType(type)) { pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("type", type)); pairs.add(new BasicNameValuePair("groupid", groupId)); pairs.add(new BasicNameValuePair("index", "0")); pairs.add(new BasicNameValuePair("message", feedback)); addTimestamp(pairs); } else { pairs = Feedback.extractPairsFromError(type, feedback, groupId, index, app); if (pairs == null) { result.success = false; result.result = null; } } HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("User-Agent", "AnkiDroid"); try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response = httpClient.execute(httpPost); Log.e(AnkiDroidApp.TAG, String.format("Bug report posted to %s", url)); int respCode = response.getStatusLine().getStatusCode(); switch (respCode) { case 200: result.success = true; result.returnType = respCode; result.result = Utils.convertStreamToString(response.getEntity().getContent()); Log.i(AnkiDroidApp.TAG, String.format("postFeedback OK: %s", result.result)); break; default: Log.e( AnkiDroidApp.TAG, String.format( "postFeedback failure: %d - %s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); result.success = false; result.returnType = respCode; result.result = response.getStatusLine().getReasonPhrase(); break; } } catch (ClientProtocolException ex) { Log.e(AnkiDroidApp.TAG, "ClientProtocolException: " + ex.toString()); result.success = false; result.result = ex.toString(); } catch (IOException ex) { Log.e(AnkiDroidApp.TAG, "IOException: " + ex.toString()); result.success = false; result.result = ex.toString(); } return result; }
/** * HTTPのGETリクエスト発行。 * * @param uri HTTPのURI * @return HTTP取得本文 */ public static String doGet(String uri) { HttpGet request = new HttpGet(uri); HttpClient httpClient = new DefaultHttpClient(); try { String body = httpClient.execute( request, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("HTTP error: " + status); } return EntityUtils.toString(response.getEntity(), "UTF-8"); } }); return body; } catch (ClientProtocolException e) { Log.e("doGet", e.toString()); throw new RuntimeException(e); } catch (IOException e) { Log.e("doGet", e.toString()); throw new RuntimeException(e); } finally { httpClient.getConnectionManager().shutdown(); } }
protected String doInBackground(String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(params[0]); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("id_vendedor", id_vendedor)); pairs.add(new BasicNameValuePair("id_cliente", id_cliente)); pairs.add(new BasicNameValuePair("descripcion", descripcion)); pairs.add(new BasicNameValuePair("id_epoca_visita", id_epoca_visita)); pairs.add(new BasicNameValuePair("valoracion", valoracion)); pairs.add(new BasicNameValuePair("fecha", fecha)); try { httppost.setEntity(new UrlEncodedFormEntity(pairs)); // HttpResponse response; httpclient.execute(httppost); } catch (ClientProtocolException e) { Toast.makeText(mContext, config.msjError(e.toString()), Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mContext, config.msjError(e.toString()), Toast.LENGTH_SHORT).show(); } return null; }
@Override protected String doInBackground(String... filePath) { File pdfFile = new File(filePath[0]); String result = "Error"; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://benybgu.appspot.com/upload"); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("uname", new StringBody("navatm")); entity.addPart("password", new StringBody("photo")); entity.addPart("path", new StringBody("???")); entity.addPart("exnum", new StringBody("1")); entity.addPart("exercise", new FileBody(pdfFile)); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { result = e.toString(); } catch (IOException e) { result = e.toString(); } } catch (Exception e) { result = e.toString(); } return result; }
public String InvokeGetFeed() { String responseString = null; HttpPost httppost = new HttpPost(Config.url_addSession); HttpClient httpclient = new DefaultHttpClient(); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new AndroidMultiPartEntity.ProgressListener() { @Override public void transferred(long num) {} }); // Adding file data to http body entity.addPart("Building_ID", new StringBody(session.getBuildingID())); entity.addPart("Point", new StringBody(session.getPoint())); entity.addPart("Floor", new StringBody(session.getFloor())); entity.addPart("Description", new StringBody(session.getDescription())); entity.addPart("Location", new StringBody(session.getLocation())); entity.addPart("Loc_Specification", new StringBody(session.getLoc_Specification())); entity.addPart("AWN_Status", new StringBody(session.getStatus_AWN())); entity.addPart("DTAC_Status", new StringBody(session.getStatus_DTAC())); entity.addPart("TRUEH_Status", new StringBody(session.getStatus_TRUEH())); entity.addPart("3BB_Status", new StringBody(session.getStatus_3BB())); entity.addPart("Remark", new StringBody(session.getRemark())); entity.addPart("Create_Date", new StringBody(session.getCreateDate().toString())); // entity.addPart("Confirm_Status",new StringBody(session.getConfirmStatus())); // entity.addPart("Confirm_Datetime",new StringBody(session.getConfirmDate().toString())); entity.addPart("User", new StringBody(session.getUser())); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; }
@Override protected String doInBackground(String... params) { String url_select = ""; for (int i = 0; i < params.length; i++) { url_select += params[i]; } ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); try { // Set up HTTP post // HttpClient is more then less deprecated. Need to change to URLConnection HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // Read content & Log inputStream = httpEntity.getContent(); } catch (UnsupportedEncodingException e1) { Log.e("UnsupportedEncodingion", e1.toString()); e1.printStackTrace(); } catch (ClientProtocolException e2) { Log.e("ClientProtocolException", e2.toString()); e2.printStackTrace(); } catch (IllegalStateException e3) { Log.e("IllegalStateException", e3.toString()); e3.printStackTrace(); } catch (IOException e4) { Log.e("IOException", e4.toString()); e4.printStackTrace(); } // Convert response to string using String Builder try { BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8); StringBuilder sBuilder = new StringBuilder(); String line; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); result = sBuilder.toString(); } catch (Exception e) { Log.e("StringBuildieredReader", "Error converting result " + e.toString()); } return result; }
protected String doInBackground(String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(params[0]); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("id_vendedor", id_vendedor)); try { httppost.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response = httpclient.execute(httppost); jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); } catch (ClientProtocolException e) { Log.e("Error ClientProtocolException", e.toString()); return "ClientProtocolException " + e.toString(); } catch (IOException e) { Log.e("Error IOException", e.toString()); return "IOException " + e.toString(); } return "ok"; }
static String doPost(String url, JSONObject postParams) { postParams = addRequiredParams(postParams); HttpResponse response; String stringResponse = null; HttpPost postRequest = new HttpPost(url); HttpClient client = new DefaultHttpClient(); try { String jsonString = postParams.toString(); postRequest.setHeader("Accept", "application/json"); postRequest.setHeader("Content-type", "application/json"); postRequest.setEntity(new StringEntity(jsonString)); response = client.execute(postRequest); stringResponse = EntityUtils.toString(response.getEntity()); } catch (org.apache.http.conn.HttpHostConnectException e) { Log.w(TAG, "No internet connection found, unable to upload events"); } catch (java.net.UnknownHostException e) { Log.w(TAG, "No internet connection found, unable to upload events"); } catch (ClientProtocolException e) { if (ZeTarget.isDebuggingOn()) { Log.e(TAG, e.toString()); } } catch (IOException e) { if (ZeTarget.isDebuggingOn()) { Log.e(TAG, e.toString()); } } catch (AssertionError e) { // This can be caused by a NoSuchAlgorithmException thrown by DefaultHttpClient if (ZeTarget.isDebuggingOn()) { Log.e(TAG, "Exception:", e); } } catch (Exception e) { // Just log any other exception so things don't crash on upload if (ZeTarget.isDebuggingOn()) { Log.e(TAG, "Exception:", e); } } finally { if (client.getConnectionManager() != null) { client.getConnectionManager().shutdown(); } } if (ZeTarget.isDebuggingOn()) { // Log.d(TAG, "Post Response is: " + stringResponse); } return stringResponse; }
@SuppressWarnings("deprecation") private String uploadFile() { String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(DataManager.FILE_UPLOAD_URL); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); File sourceFile = new File(filePath); // Adding file data to http body entity.addPart("image", new FileBody(sourceFile)); totalSize = entity.getContentLength(); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; }
public JSON(String cadena_conexion) { super(); this.cadena_conexion = cadena_conexion; HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(this.cadena_conexion); HttpResponse response; response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result = convertStreamToString(instream); this.json = new JSONObject(result); this.result = json.getString("Result"); this.json_array = json.getJSONArray("Data"); instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); this.result = "Fail: " + e.toString(); } catch (IOException e) { e.printStackTrace(); this.result = "Fail: " + e.toString(); } catch (JSONException e) { e.printStackTrace(); this.result = "Fail: " + e.toString(); } catch (Exception e) { e.printStackTrace(); this.result = "Fail: " + e.toString(); } }
@Override protected String doInBackground(Void... params) { String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(ResultListener.URL); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new AndroidMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); File sourceFile = new File(mImageUri); entity.addPart("image", new FileBody(sourceFile)); entity.addPart("action", new StringBody("uploadFile")); totalSize = entity.getContentLength(); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; }
@Override protected AppInfo doInBackground(String... params) { isRunning = true; AppInfo result = new AppInfo(); DataManager dm = new DataManager(); try { result = dm.getAppInfo(); } catch (ClientProtocolException e) { result.setFailed(true); result.setFailedReason(e.toString()); e.printStackTrace(); } catch (JSONException e) { result.setFailed(true); result.setFailedReason(e.toString()); e.printStackTrace(); } catch (IOException e) { result.setFailed(true); result.setFailedReason(e.toString()); e.printStackTrace(); } return result; }
public Object obterJson(Class<?> classe) { Object json = null; try { HttpEntity httpEntity = resposta.getEntity(); if (httpEntity != null) { Gson gson = new GsonBuilder().create(); InputStream httpEntityContent = httpEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(httpEntityContent)); json = gson.fromJson(in, classe); Log.d("erro", in.toString()); in.close(); return json; } } catch (ClientProtocolException e) { Log.d("ClientProtocolException: ", e.toString()); } catch (IOException e) { Log.d("IOException: ", e.toString()); } return json; }
@Override protected Void doInBackground(String... params) { // Instacia de Clase miFoto = params[0]; HttpClient httpClient = new DefaultHttpClient(); httpClient .getParams() .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Ruta para php HttpPost httpPost = new HttpPost("http://192.168.1.124/imegen/upload.php"); // Instancia de Clase para la foto File file = new File(miFoto); MultipartEntity multipartEntity = new MultipartEntity(); ContentBody foto = new FileBody(file, "image/jpeg"); multipartEntity.addPart("fotoUp", foto); httpPost.setEntity(multipartEntity); // Entra para ejecucion del servidor try { httpClient.execute(httpPost); httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { Log.e("Connect to /192.168.1.124:80 timed out", "Error !!" + e.toString()); e.printStackTrace(); showErrorVista(); } catch (IOException e) { Log.e("Connect to /192.168.1.124:80 timed out", "Error !!" + e.toString()); e.printStackTrace(); showErrorVista(); } return null; }
private HttpResponse makePost(String url, List<NameValuePair> nameValuePairs) { HttpPost post = new HttpPost(url); post.setHeader("User-Agent", USER_AGENT); post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); post.setHeader("Accept-Language", "en-US,en;q=0.5"); post.setHeader("Connection", "keep-alive"); post.setHeader("Referer", "https://login.iiit.ac.in"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { Log.d(TAG, e.toString()); } HttpResponse response = null; try { response = client.execute(post); } catch (ClientProtocolException e) { Log.d(TAG, e.toString()); } catch (IOException e) { Log.d(TAG, e.toString()); } return response; }
public double getDistance(GeoPoint point1, GeoPoint point2) { double distance = -1; InputStream is = null; Uri.Builder uribuilder = new Uri.Builder(); uribuilder.encodedPath(API_URL); uribuilder.appendQueryParameter( "ll1", (point1.getLatitudeE6() / 1E6) + "," + (point1.getLongitudeE6() / 1E6)); uribuilder.appendQueryParameter( "ll2", (point2.getLatitudeE6() / 1E6) + "," + (point2.getLongitudeE6() / 1E6)); String uri = uribuilder.toString(); try { HttpGet httpGet = new HttpGet(); HttpResponse response = null; httpGet.setURI(new URI(uri)); response = mHttpClient.execute(httpGet); if (response == null) { Log.w(TAG, "getDistance:Response is null"); return -1; } int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { Log.w(TAG, "getDistance:HttpStatus=" + status); return -1; } is = response.getEntity().getContent(); } catch (ClientProtocolException e) { Log.e(TAG, "getDistance:" + e.toString()); e.printStackTrace(); return -1; } catch (URISyntaxException e) { Log.e(TAG, "getDistance:" + e.toString()); e.printStackTrace(); return -1; } catch (IOException e) { Log.e(TAG, "getDistance:" + e.toString()); e.printStackTrace(); return -1; } try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, "UTF-8"); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: String tag = parser.getName(); if (tag.equals("distance")) { distance = Double.parseDouble(parser.nextText()); break; } break; } eventType = parser.next(); } if (distance < 0) { Log.w(TAG, "getDistance: Tag 'distance' not found"); return -1; } } catch (XmlPullParserException e) { Log.e(TAG, "getDistance:" + e.toString()); e.printStackTrace(); return -1; } catch (IOException e) { Log.e(TAG, "getDistance:" + e.toString()); e.printStackTrace(); return -1; } return distance; }