2016-08-21 61 views
2

我試圖向FCM發送請求到Firebase服務器,並且FCM文檔說它應該是帶有JSON數據的POST請求。這是樣本。向FCM服務器發送JSON請求不起作用

https://fcm.googleapis.com/fcm/send 
Content-Type:application/json 
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA 

{ "data": { 
    "score": "5x1", 
    "time": "15:10" 
    }, 
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." 
} 

因此,任何人都可以給出一個正確的代碼,發送POST請求與這個JSON數據?

這是我試過,但它不工作

AsyncT.java

package com.example.artin.pushnotifications; 

import android.os.AsyncTask; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.DataOutputStream; 
import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

class AsyncT extends AsyncTask<Void,Void,Void> { 

    @Override 
    protected Void doInBackground(Void... params) { 

     try { 
      URL url = new URL("https://fcm.googleapis.com/fcm/send"); //Enter URL here 
      HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); 
      httpURLConnection.setDoOutput(true); 
      httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc. 
      httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json` 
      httpURLConnection.setRequestProperty("Authorization","key=AIzaSyDZx9l_Izta9AjVS0CX70ou8OjbDVVGlHo"); 
      httpURLConnection.connect(); 

      JSONObject jsonObject = new JSONObject(); 
      JSONObject param = new JSONObject(); 
      param.put("Hii","there"); 

      jsonObject.put("data",param); 
      jsonObject.put("to", "dXazhmeFSSU:APA91bG23o75zeNOCb7pY-OCQG4BsGbY-YZrSnDrvLWv1"); 

      DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); 
      wr.writeBytes(jsonObject.toString()); 
      wr.flush(); 
      wr.close(); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 


} 

而且我執行它,當按鈕被按下

AsyncT asyncT = new AsyncT(); 
asyncT.execute(); 
+0

這麼多重複,你沒有提供你已經嘗試過。 –

+0

'排球'很好,但'OkHttp'也不錯。請參閱http://stackoverflow.com/a/36160967/2308683 –

+0

[在Android中發送POST數據]的可能重複(http://stackoverflow.com/questions/2938502/sending-post-data-in-android) –

回答

3

我用OkHttp和現在的作品被調用。這是代碼,如果有人需要它。

首先添加OkHttp到應用graddle.build

compile 'com.squareup.okhttp3:okhttp:3.4.1' 

這裏是發送POST JSON請求

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 

    OkHttpClient client = new OkHttpClient(); 

    Call post(String url, String json, Callback callback) { 
     RequestBody body = RequestBody.create(JSON, json); 
     Request request = new Request.Builder() 
       .addHeader("Content-Type","application/json") 
       .addHeader("Authorization","key=YourApiKey") 
       .url(url) 
       .post(body) 
       .build(); 
     Call call = client.newCall(request); 
     call.enqueue(callback); 
     return call; 
    } 

而剛剛創建JSON對象,並調用它,你想要的方法。

try { 
    JSONObject jsonObject = new JSONObject(); 
    JSONObject param = new JSONObject(); 
    param.put("Hii", "there"); 
    param.put("Hours", "12:50"); 
    jsonObject.put("data", param); 
    jsonObject.put("to", "TokenOfTheDevice"); 
    post("https://fcm.googleapis.com/fcm/send", jsonObject.toString(), new Callback() { 
       @Override 
       public void onFailure(Call call, IOException e) { 
        //Something went wrong 
       } 

       @Override 
       public void onResponse(Call call, Response response) throws IOException { 
        if (response.isSuccessful()) { 
         String responseStr = response.body().string(); 
         Log.d("Response", responseStr); 
         // Do what you want to do with the response. 
        } else { 
         // Request not successful 
        } 
       } 
      } 
    ); 
} catch (JSONException ex) { 
    Log.d("Exception", "JSON exception", ex); 
} 
1

這是可以做到用AsyncTask,HTTPRequest

private class PostTask extends AsyncTask<String, String, String> { 

     String Url = "//fcm.googleapis.com/fcm/send" 

     @Override 
     protected String doInBackground(String... data) { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(Url); 

     try { 
      //add data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("data", data[0])); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      //execute http post 
      HttpResponse response = httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 

     } catch (IOException e) { 

     } 
     } 
    } 

這可以通過使用 new PostTask().execute();

+1

HttpClient棄用android –

+1

@Aram Sheroyan是的,'HttpClient'已棄用,但你可以使用它。只要將compile'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'添加到您的'build.gradle'依賴項中即可。 – Stanojkovic

+1

@Stanojkovic這不是[完全正確](http://stackoverflow.com/a/32741791/2308683) –

相關問題