Url connection

Résolu/Fermé
k-23 Messages postés 252 Date d'inscription mardi 4 mars 2008 Statut Membre Dernière intervention 25 novembre 2014 - 1 nov. 2011 à 16:28
k-23 Messages postés 252 Date d'inscription mardi 4 mars 2008 Statut Membre Dernière intervention 25 novembre 2014 - 14 nov. 2011 à 15:13
Bonjour,

jai trouver un example sur le web et ca marche pas pouvez vous maider

public static void main(String[] args) throws Exception {

String url = "http://localhost:8080/";


doPost(url);

}

public static void doPost(String adresse){
OutputStreamWriter writer = null;
BufferedReader reader = null;
try {
//encodage des paramètres de la requête
String donnees = URLEncoder.encode("clef", "UTF-8")+
"="+URLEncoder.encode("valeur", "UTF-8");
donnees += "&"+URLEncoder.encode("autreClef", "UTF-8")+
"=" + URLEncoder.encode("autreValeur", "UTF-8");

//création de la connection
URL url = new URL(adresse);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);

//envoi de la requête
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(donnees);
writer.flush();

//lecture de la réponse
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try{writer.close();}catch(Exception e){}
try{reader.close();}catch(Exception e){}
}
}

public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();

if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}

// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();

conn.disconnect();
return sb.toString();
}

1 réponse

KX Messages postés 16760 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 12 février 2025 3 020
1 nov. 2011 à 17:47
Tu prends un petit bout de code par ici, un autre petit bout de code par là, tu mélanges le tout, et ça marche pas ? C'est vraiment bizarre, moi qui pensait que Google faisait tout !

Que veux tu faire !?

Si tu cherches de la documentation tu trouveras, visiblement tu connais bien Google, il n'y a plus qu'à s'en servir correctement :
oracle --> Lesson: Working with URLs
eTeks --> Les accès au réseau
0
k-23 Messages postés 252 Date d'inscription mardi 4 mars 2008 Statut Membre Dernière intervention 25 novembre 2014 9
8 nov. 2011 à 16:08
voici jai trouvé qqch dinteressant ce que je voulais faire voila:

class Program
{
static void Main(string[] args)
{
ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8001");
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
IService channel = cf.CreateChannel();

String donnee = channel.ToString() ;
Console.WriteLine(donnee);
Console.WriteLine( cf.ToString());



Console.WriteLine(channel.GetMessage("Dhananjay Get","12","13","14"));
Console.WriteLine(channel.PostMessage("Dhananjay Post"));
Console.Read();

}
}

class Program
{
static void Main(string[] args)
{

WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8001"));
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>();
stp.HttpHelpPageEnabled = false;
host.Open();
Console.WriteLine("Service is up and running");
Console.WriteLine("Press enter to quit ");

ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8001");
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
IService channel = cf.CreateChannel();





Console.ReadLine();
host.Close();
}
}

Bon voila ma derniere class cest un serveur lui il possede de service le voila

namespace Contracts
{
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet]
string GetMessage(string facteurDeCharge, string temperatureAmbiante, string temperatureHuile, string temperaturePointChaud);

[OperationContract]
[WebGet]
List<double> affiche();
/*

/*
[OperationContract]
[WebGet]
string Get(string inputMessage);
*/
[OperationContract]
[WebInvoke]
string PostMessage(string facteurDeCharge);
}
}

ces services sont develloper dans une autre class

public class Service : IService
{
int t = 5;
public string facteur="---";

public List<double> list;

public List<double> List
{
get
{
if (list== null) //si la liste est null on la crée
{
//https://fr.wikipedia.org/wiki/Box-office_fran%C3%A7ais
list = new List<double> ();

list.Add(12.2);


};
//on crée l'uri pour accéder à la ressource


return list;
}
}

public string GetMessage(string facteurDeCharge, string temperatureAmbiante, string temperatureHuile, string temperaturePointChaud)
{

Console.WriteLine( facteurDeCharge + "\n " + temperatureAmbiante + "\n" + temperatureHuile + "\n " + temperaturePointChaud + "\n");
//return "Calling Get for you " + facteurDeCharge + temperatureAmbiante + temperatureHuile + temperaturePointChaud;
facteur = temperatureAmbiante;

if (list == null)
{
list = new List<double>();

}
list.Add(t);
Console.WriteLine(list.Count());
return "Calling Get for you ";
}
public string PostMessage(string facteurDeCharge)
{

//list.Add(2.3);
return "Calling Post for you " + facteurDeCharge;
}

public List<double> affiche()
{
if (list == null)
{
list = new List<double>();
}
return list;


}

public List<double> affiche1()
{

if (list == null)
{
list = new List<double>();
}
return list;

}

}

Donc mon serveur peut se connecter a tous le client du meme port.

mon but ici est de pouvoir prendre ces donnees pour qu'apres je puisse faire n'importe quoi
par example lutiliser dans une fonction. dans ma methode getmessage je suis capable d'afficher les donner recu mais je peux pas les reutiliser en dehors de cette fonction viola mon probleme.

le programme est faite en c# et jutiliser le mode de communication http REST

merci.
0
k-23 Messages postés 252 Date d'inscription mardi 4 mars 2008 Statut Membre Dernière intervention 25 novembre 2014 9
14 nov. 2011 à 15:13
la réponse na pas été evidente mais la voila il me fallait un ceci en haut de ma classe service
pour que mes valeur garde la valeur qu'on lui affecte

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
0