Search in sources :

Example 11 with UrlEncodedFormEntity

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

the class HttpRequest2 method send.

public String send() {
    client = AndroidHttpClient.newInstance("Android");
    HttpPost request = new HttpPost(url);
    if (params != null) {
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
            entity.setContentEncoding(HTTP.UTF_8);
            request.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            Log.e("", "UnsupportedEncodingException: " + e);
        }
    }
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = "";
    try {
        response = client.execute(request, responseHandler);
    } catch (ClientProtocolException e) {
        Log.e("HttpRequest2", e.toString());
    } catch (IOException e) {
        Log.e("HttpRequest2", e.toString());
    }
    if (LOG_RESPONSE == true)
        Log.i("HttpRequest2", response);
    if (HTML_TRANSFORM == true)
        response = Html.fromHtml(response).toString();
    close();
    return response;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) ArrayList(java.util.ArrayList) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map)

Example 12 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project Talon-for-Twitter by klinker24.

the class TwitLongerHelper method postToTwitLonger.

/**
     * Posts the status to twitlonger
     * @return returns an object containing the shortened text and the id for the twitlonger url
     */
public TwitLongerStatus postToTwitLonger() {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-API-KEY", TWITLONGER_API_KEY);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("content", tweetText));
        if (replyToId != 0) {
            nvps.add(new BasicNameValuePair("reply_to_id", String.valueOf(replyToId)));
        } else if (replyToScreenname != null) {
            nvps.add(new BasicNameValuePair("reply_to_screen_name", replyToScreenname));
        }
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        String content = "";
        String id = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }
        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            content = jsonObject.getString("tweet_content");
            id = jsonObject.getString("id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitlonger", "content: " + content);
        Log.v("talon_twitlonger", "id: " + id);
        return new TwitLongerStatus(content, id);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) JSONObject(org.json.JSONObject) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader)

Example 13 with UrlEncodedFormEntity

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

the class FormParamProcessor method process.

/**
	 * <p>Accepts the {@link InvocationContext} with an {@link HttpEntityEnclosingRequestBase} and 
	 * creates a list of <a href="http://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms">
	 * form-urlencoded</a> name-value pairs using arguments annotated with @{@link FormParam} and 
	 * @{@link FormParams}. It's then inserted to the body of the request being processed.</p>
	 * 
	 * <p><b>Note</b> that any {@link HttpRequestBase}s which aren't {@link HttpEntityEnclosingRequestBase}s 
	 * will be ignored.</p>
	 * 
	 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
	 * 
	 * @param context
	 * 			the {@link InvocationContext} which is used to discover any annotated form parameters 
	 * <br><br>
	 * @param request
	 * 			prefers an instance of {@link HttpPost} so as to conform with HTTP 1.1; however, other  
	 * 			{@link HttpEntityEnclosingRequestBase}s will be entertained to allow compliance with 
	 * 			unusual endpoint definitions (as long as they are {@link HttpEntityEnclosingRequestBase}s) 
	 * <br><br>
 	 * @return the same instance of {@link HttpRequestBase} which was given for processing form parameters 
	 * <br><br>
	 * @throws RequestProcessorException
	 * 			if a form parameters failed to be created and inserted into the request body
	 * <br><br>
	 * @since 1.3.0
	 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {
    try {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
            //add static name and value pairs
            List<Param> constantFormParams = RequestUtils.findStaticFormParams(context);
            for (Param param : constantFormParams) {
                nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
            }
            //add individual name and value pairs
            List<Entry<FormParam, Object>> formParams = Metadata.onParams(FormParam.class, context);
            for (Entry<FormParam, Object> entry : formParams) {
                String name = entry.getKey().value();
                Object value = entry.getValue();
                if (!(value instanceof CharSequence)) {
                    StringBuilder errorContext = new StringBuilder().append("Form (url-encoded) parameters can only be of type ").append(CharSequence.class.getName()).append(". Please consider implementing CharSequence ").append("and providing a meaningful toString() representation for the ").append("<name> of the form parameter. ");
                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }
                nameValuePairs.add(new BasicNameValuePair(name, String.valueOf(value)));
            }
            //add batch name and value pairs (along with any static params)
            List<Entry<FormParams, Object>> queryParamMaps = Metadata.onParams(FormParams.class, context);
            for (Entry<FormParams, Object> entry : queryParamMaps) {
                Param[] constantParams = entry.getKey().value();
                if (constantParams != null && constantParams.length > 0) {
                    for (Param param : constantParams) {
                        nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
                    }
                }
                Object map = entry.getValue();
                if (!(map instanceof Map)) {
                    StringBuilder errorContext = new StringBuilder().append("@FormParams can only be applied on <java.util.Map>s. ").append("Please refactor the method to provide a Map of name and value pairs. ");
                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }
                Map<?, ?> nameAndValues = (Map<?, ?>) map;
                for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {
                    Object name = nameAndValue.getKey();
                    Object value = nameAndValue.getValue();
                    if (!(name instanceof CharSequence && (value instanceof CharSequence || value instanceof Collection))) {
                        StringBuilder errorContext = new StringBuilder().append("The <java.util.Map> identified by @FormParams can only contain mappings of type ").append("<java.lang.CharSequence, java.lang.CharSequence> or ").append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");
                        throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                    }
                    if (value instanceof CharSequence) {
                        nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(), ((CharSequence) value).toString()));
                    } else {
                        //add multi-valued form params 
                        Collection<?> multivalues = (Collection<?>) value;
                        for (Object multivalue : multivalues) {
                            if (!(multivalue instanceof CharSequence)) {
                                StringBuilder errorContext = new StringBuilder().append("Values for the <java.util.Map> identified by @FormParams can only contain collections ").append("of type java.util.Collection<? extends CharSequence>");
                                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                            }
                            nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(), ((CharSequence) multivalue).toString()));
                        }
                    }
                }
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
            urlEncodedFormEntity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
        return request;
    } catch (Exception e) {
        throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e : new RequestProcessorException(context, getClass(), e);
    }
}
Also used : Entry(java.util.Map.Entry) FormParams(com.lonepulse.robozombie.annotation.FormParams) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) LinkedList(java.util.LinkedList) FormParam(com.lonepulse.robozombie.annotation.FormParam) Param(com.lonepulse.robozombie.annotation.Param) Collection(java.util.Collection) FormParam(com.lonepulse.robozombie.annotation.FormParam) Map(java.util.Map)

Example 14 with UrlEncodedFormEntity

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

the class AjaxLoadingActivity method async_post_entity.

/*
	public void async_post2(){
		
        String url = "your url";
		
        //get your byte array or file
        byte[] data = new byte[1000];
        
		Map<String, Object> params = new HashMap<String, Object>();
		
		//put your post params
		params.put("paramName", data);
		
		AjaxCallback<byte[]> cb = new AjaxCallback<byte[]>() {

            @Override
            public void callback(String url, byte[] data, AjaxStatus status) {
               
            	System.out.println(data);
            	System.out.println(status.getCode() + ":" + status.getError());
                
            	
            }
        };
        
        cb.url(url).type(byte[].class);
        
        //set Content-Length header
        cb.params(params).header("Content-Length", Integer.toString(data.length));
		cb.async(this);
		
	}
	*/
public void async_post_entity() throws UnsupportedEncodingException {
    String url = "http://search.twitter.com/search.json";
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("q", "androidquery"));
    HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AQuery.POST_ENTITY, entity);
    aq.progress(R.id.progress).ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) {
            showResult(json, status);
        }
    });
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JSONObject(org.json.JSONObject) AjaxStatus(com.androidquery.callback.AjaxStatus)

Example 15 with UrlEncodedFormEntity

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

the class AQueryAsyncTest method testAjaxPostRaw.

public void testAjaxPostRaw() throws UnsupportedEncodingException {
    String url = "http://www.androidquery.com/p/doNothing";
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("q", "androidquery"));
    HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AQuery.POST_ENTITY, entity);
    aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

        @Override
        public void callback(String url, JSONObject jo, AjaxStatus status) {
            done(url, jo, status);
        }
    });
    waitAsync();
    JSONObject jo = (JSONObject) result;
    assertNotNull(jo);
    assertNotNull(jo.opt("params"));
    assertEquals("POST", jo.optString("method"));
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) AjaxStatus(com.androidquery.callback.AjaxStatus)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)127 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)105 HttpPost (org.apache.http.client.methods.HttpPost)99 NameValuePair (org.apache.http.NameValuePair)94 ArrayList (java.util.ArrayList)91 HttpResponse (org.apache.http.HttpResponse)71 IOException (java.io.IOException)45 HttpEntity (org.apache.http.HttpEntity)39 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)23 Test (org.junit.Test)20 HttpClient (org.apache.http.client.HttpClient)19 HttpGet (org.apache.http.client.methods.HttpGet)19 JSONObject (org.json.JSONObject)17 Map (java.util.Map)16 TestHttpClient (io.undertow.testutils.TestHttpClient)14 Header (org.apache.http.Header)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HashMap (java.util.HashMap)12