# curl request in java umwandeln



## themazreku1 (29. Mai 2015)

Hallo Zusammen

Ich  habe folgende cURL request:

curl -ikX POST -d "{\"outboundSMSMessageRequest\":{\"senderAddress\":\"tel:+40000000000\", \"address\":[\"tel:+4179xxxxxxx\"],\"outboundSMSTextMessage\":{\"message\":\"The Message\"},\"clientCorrelator\":\"any id\"}}" -H "Content-Type:application/json" -H "Accept:application/json" -H "client_id: %YOUR_CLIENT_ID%" https://api.swisscom.com/v1/messaging/sms/outbound/tel:+40000000000/requests

Meine Aufgabe ist es, dass in Java zu realisierten, also eine Java Klasse zu schreiben. 

Ich habe folgende Java-Klasse geschrieben: 


```
package sms;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
 
import com.google.gson.Gson;
 
 
/**
 * 
 * @author Behar
 * Sms senden 
 */
public class Sms {
    
     private String to;  //Telefonnummer
     private String text; //Nachricht
     private int tokenLength;  //??
     private String expireTime; //?
      
    
    
     /**
      * @param apiKey
      * @param sms
      * @throws IOException 
      */
     public static void senden (String apiKey, Sms sms) throws IOException {
         try{
              //Json Parameter erstellen 
              Gson gson = new Gson();
              String json = gson.toJson(sms);
             
              //URL 
              URL url = new URL("https://api.swisscom.com/v1/"); 
             
              //Verbindung offnen 
              HttpURLConnection con = (HttpURLConnection) url.openConnection();
             
              //Methode
              con.setRequestMethod("POST");
              //Header setezn 
              con.setRequestProperty("client_id", apiKey);
              con.setRequestProperty("Accept", "application/json; charset=utf-8");
              con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
             
              con.setDoOutput(true);
             
              //Json data im Body hinzufügen 
              DataOutputStream wr = new DataOutputStream(con.getOutputStream());
             String param = "json=" + URLEncoder.encode(json, "UTF-8");
             wr.write(param.getBytes());
            
             System.out.println(json);
             wr.flush();
             wr.close();
            
          // Get the response
            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);
 
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
 
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
 
            // 7. Print result
            System.out.println(response.toString());
             
         }
         catch (MalformedURLException e) {
               e.printStackTrace();
         }
        
     } 
    
     //Getter und  Setter Methoden 
    
     /**
      * 
      * @return Nachricht 
      */
     public String getTo() {
         return to;
     }
    
     /**
      * 
      * @param to Telefonnummer des Senders 
      */
     public void setTo(String to) {
         this.to = to;
     }
    
     /**
      * @return Nachricht
      */
     public String getText() {
         return text;
     }
    
     public void setText(String text) {
         this.text = text;
     }
    
     public int getTokenLength() {
         return tokenLength;
     }
    
     public void setTokenLength(int tokenLength) {
         this.tokenLength = tokenLength;
     }
    
     public String getExpireTime() {
         return expireTime;
     }
    
     public void setExpireTime(String expireTime) {
         this.expireTime = expireTime;
     }
 
}
```
 
Leider funktioniert die Klasse nicht ganz. 
Ich bekomme Response Code : 400

Ich glaube es stimmt mit den Parametern etwas nicht.  

Klasse senden: 


```
[COLOR=#931A68]package[COLOR=#000000] sms;[/COLOR][/COLOR]


[COLOR=#931a68]import[/COLOR] java.io.IOException;


[COLOR=#931A68]public[COLOR=#000000] [/COLOR]class[COLOR=#000000] [/COLOR][COLOR=#000000][U]Send[/U][/COLOR][COLOR=#000000] {[/COLOR][/COLOR]
	
	[COLOR=#931a68]public[/COLOR] [COLOR=#931a68]static[/COLOR] [COLOR=#931a68]void[/COLOR] [U]main (String [] arg) [/U][COLOR=#931a68][U]throws[/U][/COLOR][U] IOException[/U] {
	
		Sms sms = [COLOR=#931a68]new[/COLOR] Sms(); 
		sms.setText([COLOR=#3933ff]"Hallo Test"[/COLOR]);
		sms.setTo([COLOR=#3933ff]"+41791749697"[/COLOR]);
		sms.setTokenLength(8);
		sms.setExpireTime([COLOR=#3933ff]"60"[/COLOR]);
		
		Sms.senden([COLOR=#3933ff]"?? :)"[/COLOR], sms);
	}


}
```
 
Ich wäre euch sehr dankbar wenn ihr mir weiterhelfen könntet

Danke im Voraus!


----------



## fhoffmann (29. Mai 2015)

du solltest eine HttpsURLConnection benutzen.


----------



## themazreku1 (29. Mai 2015)

Das benutze ich doch!

//Json Parameter erstellen 
            Gson gson = new Gson();
            String json = gson.toJson(sms);

//URL 
            URL url = new URL("https://api.swisscom.com/v1/"); 

//Verbindung offnen 
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

//Methode
            con.setRequestMethod("POST");
//Header setezn 
            con.setRequestProperty("client_id", apiKey);
            con.setRequestProperty("Accept", "application/json; charset=utf-8");
            con.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            con.setDoOutput(true);

//Json data im Body hinzufügen 
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            String param = "json=" + URLEncoder.encode(json, "UTF-8");
            wr.write(param.getBytes());

            System.out.println(json);
            wr.flush();
            wr.close();


----------



## fhoffmann (29. Mai 2015)

du benutzt eine HttpURLConnection  (ohne "s")
Da die URL mit "https" beginnt, kannst du auch zu einer HttpsURLConnection  casten:
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();


----------



## themazreku1 (29. Mai 2015)

Achso, ja danke
Ich habe es geändert, aber ich bekomme trotzdem ein Response Code : 401

Es stimmt mit dem Request etwas nicht. 

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.swisscom.com/v1/
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
	at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1514)
	at java.security.AccessController.doPrivileged(Native Method)
	at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1508)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1162)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
	at sms.Sms.senden(Sms.java:73)
	at sms.Send.main(Send.java:15)
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.swisscom.com/v1/
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1459)
	at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:318)
	at sms.Sms.senden(Sms.java:68)
	... 1 more


----------

