Search in sources :

Example 6 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project jstorm by alibaba.

the class HttpClientService method excutePost.

protected String excutePost(String url, List<NameValuePair> nvps) throws Exception {
    HttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    String response = parseResponse(url, httpResponse);
    return response;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 7 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project android-instagram by markchang.

the class TakePictureActivity method doUpload.

// fixme: this doesn't need to be a Map return
public Map<String, String> doUpload() {
    Log.i(TAG, "Upload");
    Long timeInMilliseconds = System.currentTimeMillis() / 1000;
    String timeInSeconds = timeInMilliseconds.toString();
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Map returnMap = new HashMap<String, String>();
    // check for cookies
    if (httpClient.getCookieStore() == null) {
        returnMap.put("result", "Not logged in");
        return returnMap;
    }
    try {
        // create multipart data
        File imageFile = new File(processedImageUri.getPath());
        FileBody partFile = new FileBody(imageFile);
        StringBody partTime = new StringBody(timeInSeconds);
        multipartEntity.addPart("photo", partFile);
        multipartEntity.addPart("device_timestamp", partTime);
    } catch (Exception e) {
        Log.e(TAG, "Error creating mulitpart form: " + e.toString());
        returnMap.put("result", "Error creating mulitpart form: " + e.toString());
        return returnMap;
    }
    // upload
    try {
        HttpPost httpPost = new HttpPost(Utils.UPLOAD_URL);
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        Log.i(TAG, "Upload status: " + httpResponse.getStatusLine());
        // test result code
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.e(TAG, "Login HTTP status fail: " + httpResponse.getStatusLine().getStatusCode());
            returnMap.put("result", "HTTP status error: " + httpResponse.getStatusLine().getStatusCode());
            return returnMap;
        }
        /*
            {"status": "ok"}
            */
        if (httpEntity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
            String json = reader.readLine();
            JSONTokener jsonTokener = new JSONTokener(json);
            JSONObject jsonObject = new JSONObject(jsonTokener);
            Log.i(TAG, "JSON: " + jsonObject.toString());
            String loginStatus = jsonObject.getString("status");
            if (!loginStatus.equals("ok")) {
                Log.e(TAG, "JSON status not ok: " + jsonObject.getString("status"));
                returnMap.put("result", "JSON status not ok: " + jsonObject.getString("status"));
                return returnMap;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "HttpPost exception: " + e.toString());
        returnMap.put("result", "HttpPost exception: " + e.toString());
        return returnMap;
    }
    // configure / comment
    try {
        HttpPost httpPost = new HttpPost(Utils.CONFIGURE_URL);
        String partComment = txtCaption.getText().toString();
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("device_timestamp", timeInSeconds));
        postParams.add(new BasicNameValuePair("caption", partComment));
        httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        // test result code
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.e(TAG, "Upload comment fail: " + httpResponse.getStatusLine().getStatusCode());
            returnMap.put("result", "Upload comment fail: " + httpResponse.getStatusLine().getStatusCode());
            return returnMap;
        }
        returnMap.put("result", "ok");
        return returnMap;
    } catch (Exception e) {
        Log.e(TAG, "HttpPost comment error: " + e.toString());
        returnMap.put("result", "HttpPost comment error: " + e.toString());
        return returnMap;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project android-instagram by markchang.

the class Utils method doRestulPut.

public static String doRestulPut(DefaultHttpClient httpClient, String url, List<NameValuePair> postParams, Context ctx) {
    // create POST
    HttpPost httpPost = new HttpPost(url);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // test result code
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.i(TAG, "Login HTTP status fail");
            return null;
        }
        // test json response
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
            String json = reader.readLine();
            JSONTokener jsonTokener = new JSONTokener(json);
            JSONObject jsonObject = new JSONObject(jsonTokener);
            Log.i(TAG, "JSON: " + jsonObject.toString());
            String loginStatus = jsonObject.getString("status");
            if (!loginStatus.equals("ok")) {
                Log.e(TAG, "JSON status not ok: " + jsonObject.getString("status"));
                return null;
            } else {
                return json;
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        Log.e(TAG, "HttpPost error: " + e.toString());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "JSON parse error: " + e.toString());
        return null;
    }
}
Also used : JSONTokener(org.json.JSONTokener) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) JSONObject(org.json.JSONObject) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 9 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project camel by apache.

the class RestletPostFormTest method testPostBody.

@Test
public void testPostBody() throws Exception {
    HttpUriRequest method = new HttpPost("http://localhost:" + portNum + "/users");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("foo", "bar"));
    ((HttpEntityEnclosingRequestBase) method).setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response = doExecute(method);
    assertHttpResponse(response, 200, "text/plain");
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) Test(org.junit.Test)

Example 10 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project FBReaderJ by geometer.

the class ZLNetworkManager method perform.

void perform(ZLNetworkRequest request, BearerAuthenticator authenticator, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
    boolean success = false;
    DefaultHttpClient httpClient = null;
    HttpEntity entity = null;
    try {
        final HttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, CookieStore);
        request.doBefore();
        final HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
        httpClient = new DefaultHttpClient(params) {

            protected AuthenticationHandler createTargetAuthenticationHandler() {
                final AuthenticationHandler base = super.createTargetAuthenticationHandler();
                return new AuthenticationHandler() {

                    public Map<String, Header> getChallenges(HttpResponse response, HttpContext context) throws MalformedChallengeException {
                        return base.getChallenges(response, context);
                    }

                    public boolean isAuthenticationRequested(HttpResponse response, HttpContext context) {
                        return base.isAuthenticationRequested(response, context);
                    }

                    public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context) throws AuthenticationException {
                        try {
                            return base.selectScheme(challenges, response, context);
                        } catch (AuthenticationException e) {
                            final Header bearerHeader = challenges.get("bearer");
                            if (bearerHeader != null) {
                                String realm = null;
                                for (HeaderElement elt : bearerHeader.getElements()) {
                                    final String name = elt.getName();
                                    if (name == null) {
                                        continue;
                                    }
                                    if ("realm".equals(name) || name.endsWith(" realm")) {
                                        realm = elt.getValue();
                                        break;
                                    }
                                }
                                throw new BearerAuthenticationException(realm, response.getEntity());
                            }
                            throw e;
                        }
                    }
                };
            }
        };
        final HttpRequestBase httpRequest;
        if (request instanceof ZLNetworkRequest.Get) {
            httpRequest = new HttpGet(request.URL);
        } else if (request instanceof ZLNetworkRequest.PostWithBody) {
            httpRequest = new HttpPost(request.URL);
            ((HttpPost) httpRequest).setEntity(new StringEntity(((ZLNetworkRequest.PostWithBody) request).Body, "utf-8"));
        /*
					httpConnection.setRequestProperty(
						"Content-Length",
						Integer.toString(request.Body.getBytes().length)
					);
				*/
        } else if (request instanceof ZLNetworkRequest.PostWithMap) {
            final Map<String, String> parameters = ((ZLNetworkRequest.PostWithMap) request).PostParameters;
            httpRequest = new HttpPost(request.URL);
            final List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(parameters.size());
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        } else if (request instanceof ZLNetworkRequest.FileUpload) {
            final ZLNetworkRequest.FileUpload uploadRequest = (ZLNetworkRequest.FileUpload) request;
            final File file = ((ZLNetworkRequest.FileUpload) request).File;
            httpRequest = new HttpPost(request.URL);
            final MultipartEntity data = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));
            data.addPart("file", new FileBody(uploadRequest.File));
            ((HttpPost) httpRequest).setEntity(data);
        } else {
            throw new ZLNetworkException("Unknown request type");
        }
        httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent());
        if (!request.isQuiet()) {
            httpRequest.setHeader("X-Accept-Auto-Login", "True");
        }
        httpRequest.setHeader("Accept-Encoding", "gzip");
        httpRequest.setHeader("Accept-Language", ZLResource.getLanguage());
        for (Map.Entry<String, String> header : request.Headers.entrySet()) {
            httpRequest.setHeader(header.getKey(), header.getValue());
        }
        httpClient.setCredentialsProvider(new MyCredentialsProvider(httpRequest, request.isQuiet()));
        final HttpResponse response = execute(httpClient, httpRequest, httpContext, authenticator);
        entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            final AuthState state = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (state != null) {
                final AuthScopeKey key = new AuthScopeKey(state.getAuthScope());
                if (myCredentialsCreator.removeCredentials(key)) {
                    entity = null;
                }
            }
        }
        final int responseCode = response.getStatusLine().getStatusCode();
        InputStream stream = null;
        if (entity != null && (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL)) {
            stream = entity.getContent();
        }
        if (stream != null) {
            try {
                final Header encoding = entity.getContentEncoding();
                if (encoding != null && "gzip".equalsIgnoreCase(encoding.getValue())) {
                    stream = new GZIPInputStream(stream);
                }
                request.handleStream(stream, (int) entity.getContentLength());
            } finally {
                stream.close();
            }
            success = true;
        } else {
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new ZLNetworkAuthenticationException();
            } else {
                throw new ZLNetworkException(response.getStatusLine().toString());
            }
        }
    } catch (ZLNetworkException e) {
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        final String code;
        if (e instanceof UnknownHostException) {
            code = ZLNetworkException.ERROR_RESOLVE_HOST;
        } else {
            code = ZLNetworkException.ERROR_CONNECT_TO_HOST;
        }
        throw ZLNetworkException.forCode(code, ZLNetworkUtil.hostFromUrl(request.URL), e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ZLNetworkException(e.getMessage(), e);
    } finally {
        request.doAfter(success);
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
            }
        }
    }
}
Also used : BasicHttpContext(org.apache.http.protocol.BasicHttpContext) GZIPInputStream(java.util.zip.GZIPInputStream) StringEntity(org.apache.http.entity.StringEntity) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AuthenticationHandler(org.apache.http.client.AuthenticationHandler) FileBody(org.apache.http.entity.mime.content.FileBody) GZIPInputStream(java.util.zip.GZIPInputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)134 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)111 HttpPost (org.apache.http.client.methods.HttpPost)105 NameValuePair (org.apache.http.NameValuePair)100 ArrayList (java.util.ArrayList)96 HttpResponse (org.apache.http.HttpResponse)74 IOException (java.io.IOException)47 HttpEntity (org.apache.http.HttpEntity)40 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)31 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)26 HttpClient (org.apache.http.client.HttpClient)20 Test (org.junit.Test)20 HttpGet (org.apache.http.client.methods.HttpGet)19 Map (java.util.Map)18 JSONObject (org.json.JSONObject)18 TestHttpClient (io.undertow.testutils.TestHttpClient)14 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashMap (java.util.HashMap)13 Header (org.apache.http.Header)13