4

I had change from API23 to 22 because they said httpclient wasn't available.When I switched to API22 I had problem with HttpClient,HttpPost and NameValuePair.I found the solution to use HttpURLConnectionHandler.But I don't know how to use it for the following method.

 public void send(View v)
{

    HttpClient httpclient = new DefaultHttpClient();
    // put the address to your server and receiver file here
    HttpPost httppost = new HttpPost("http://yoursite/yourPHPScript.php");
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        // we wont be receiving the parameter ID in your server, but it is here to show you how you can send more data
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        // message is the parameter we are receiving, it has the value of 1 which is the value that will be sent from your server to your Arduino board
        nameValuePairs.add(new BasicNameValuePair("message", "1"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpclient.execute(httppost); // send the parameter to the server
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

Someone kindly help me

Shrei
  • 55
  • 2
  • 6
  • What exactly are you trying to do, and what specifically is it that you are having trouble with? (What error messages are you getting.) – Lilith Daemon Apr 11 '16 at 01:02
  • HttpPost,HttpClient and NameValuePair are deprecated.I need to use this post method with the HttpURLConnectionHandler Class which I already have @ChrisBritt – Shrei Apr 11 '16 at 01:04

1 Answers1

4

You can do something like this:

public boolean sendPost(MessageSenderContent content) {

        HttpURLConnection connection;
        try {
            URL gcmAPI = new URL("your_url");
            connection = (HttpURLConnection) gcmAPI.openConnection();

            connection.setRequestMethod("POST");// type of request
            connection.setRequestProperty("Content-Type", "application/json");//some header you want to add
            connection.setRequestProperty("Authorization", "key=" + AppConfig.API_KEY);//some header you want to add
            connection.setDoOutput(true);

            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
            //content is the object you want to send, use instead of NameValuesPair
            mapper.writeValue(dataOutputStream, content);

            dataOutputStream.flush();
            dataOutputStream.close();

            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (responseCode == 200) {
            Log.i("Request Status", "This is success response status from server: " + responseCode);
            return true;
        } else {
            Log.i("Request Status", "This is failure response status from server: " + responseCode);
            return false;
        }
}

Example for MessageSenderContent, than you can create your own one for "message" and "id":

public class MessageSenderContent implements Serializable {
    private List<String> registration_ids;
    private Map<String, String> data;

    public void addRegId(String regId){
        if (registration_ids==null){
            registration_ids = new LinkedList<>();
            registration_ids.add(regId);
        }
    }

    public void createData(String title,String message) {
        if (data == null)
            data = new HashMap<>();

        data.put("title", title);
        data.put("message", message);
    }

    public Map<String, String> getData() {
        return data;
    }

    public void setData(Map<String, String> data) {
        this.data = data;
    }

    public List<String> getRegIds() {
        return registration_ids;
    }

    public void setRegIds(List<String> regIds) {
        this.registration_ids = regIds;
    }

    @Override
    public String toString() {
        return "MessageSenderContent{" +
                "registration_ids=" + registration_ids +
                ", data=" + data +
                '}';
    }

UPDATE:

You can use HttpUrlConnection after import this in your build.gradle file

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"
    useLibrary 'org.apache.http.legacy' // this one will let you use HttpUrlConnection
    packagingOptions {
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
}
    ...
}
Bui Quang Huy
  • 1,784
  • 2
  • 17
  • 50
  • Thanks a lot ! But can I also get HttpURLConnection class that you used? – Shrei Apr 11 '16 at 01:32
  • It says 'Warning:Unable to find optional library: org.apache.http.legacy'.And setRequestmethod,setRequestProperty methods couldn't be resolved – Shrei Apr 11 '16 at 01:42
  • It couldn't be resovle because you haven't import that library success yet. I updated my answer, besides, you can take a look on this: http://stackoverflow.com/questions/30856785/how-to-add-apache-http-api-legacy-as-compile-time-dependency-to-build-grade-fo – Bui Quang Huy Apr 11 '16 at 01:44
  • The update makes no sense, HttpUrlConnection has nothing to do with the legacy Apache stuff – Daniel Nugent Apr 11 '16 at 02:57